/**
 * The base utilities for plugin development
 */
define('seaplugin/plugin-base', [], function(require, exports) {
  var $ = require('commplugin/jquery');
  var pluginSDK = seajs.pluginSDK
  var util = pluginSDK.util
  var Module = pluginSDK.Module
  var pluginsInfo = {}
  var uriCache = {}
  //配置信息
  var config={};

  exports.add = function(o) {
    pluginsInfo[o.name] = o
  }
  
  /**
   * base初始化
   */
  exports.init = function(obj) {
  	obj.$(window).bind('hashchange', function(e) {
		var hash = _parseParam(location.hash);
		if (hash.action) {
			obj.actionControl[hash.action](hash);
		}
	});
  }
  exports.config=config;
  config.dataUrl="http://192.168.5.30:8080/jban/";

  exports.util = {
    xhr: xhr,
    globalEval: globalEval,
    parseParam : _parseParam,
    getResult:_getResult
  }
  
  /**
   * 通过ajax获得数据
   */
  
  function _getResult(opt){
  	opt = $.extend({
		dataType : "json",
		contentType : "application/x-www-form-urlencoded;charset=UTF-8",
		success : function(result) {
		},
		error : function(xhr) {
			
		}
	}, opt);
	opt.url = config.dataUrl+opt.url,
	$.ajax(opt);
  }
  
  

  /*--自定义方法  -----*/
  /**
	 * @description 将?key1=value1&key2=value2&...转换成一个对象{key1:value1,key2:value2....}
	 * @param {String}
	 *            string String字符串
	 * @return {Object} obj 返回结果 {key1:value1,key2:value2....}
	 */
  function _parseParam(str){
	var obj = {};
	if(str==undefined || str==null){
		return obj;	
	}
	
	if(typeof str =='object'){
		return str;
	}
	
	if(typeof str =='string'){
		str = decodeURIComponent(str);
	}
			
	// 踢出前缀#或者？
	str = str.replace(/^[\?\#]/,"");
	// 分割参数
	var params = str.split("&");
	
	for(var i=0;i<params.length;i++){
		var item = params[i].split("=");
		var key = item[0];
        var val = item[1];
		
		if(!key){
			continue;	
		}
		
		// 类型转换
		if(val == undefined){
			val = true;
		}else{
			val = _parseAny(val);
		}
		obj[key] = val;
	}
	return obj;
}


/**
 * @description 把字符串自动转换成它原来的类型
 * @param val
 *            o 任意对象
 * @return val any
 */
	function _parseAny(val){			
		if(typeof val =='string'){
			if(val!="" && !isNaN(val)){
				val = val-0;
			}
			else if(val.toLowerCase()=="true"){
				val = true;
			}
			else if(val.toLowerCase()=="false"){
				val = false;
			}
		}
		return val;
	}
  /*--自定义方法  end -----*/
  

  extendResolve()
  extendFetch()


  function extendResolve() {
    var _resolve = Module._resolve

    Module._resolve = function(id, refUri) {
      var pluginName

      if (/\.\w|^\w+!/.test(id)) {
        var m

        // id = text!path/to/some
        if (m = id.match(/^(\w+)!(.*)$/)) {
          pluginName = m[1]
          id = m[2]
        }
        // id = abc.xyz?t=123
        else if ((m = id.match(/[^?]*(\.\w+)/))) {
          var ext = m[1]
          for (var k in pluginsInfo) {

            if (pluginsInfo.hasOwnProperty(k) &&
                util.indexOf(pluginsInfo[k].ext, ext) > -1) {
              pluginName = k
              break
            }
          }
        }

        // Prevents adding the default `.js` extension
        if (pluginName && !/\?|#$/.test(id)) {
          id += '#'
        }
      }

      var uri = _resolve(id, refUri)

      if (pluginName && pluginsInfo[pluginName] && !uriCache[uri]) {
        uriCache[uri] = pluginName
      }

      return uri
    }
  }


  function extendFetch() {
    var _fetch = Module._fetch

    Module._fetch = function(url, callback, charset) {
      var pluginName = uriCache[util.unParseMap(url)]

      if (pluginName) {
        pluginsInfo[pluginName].fetch(url, callback, charset)
        return
      }

      _fetch(url, callback, charset)
    }
  }


  function xhr(url, callback) {
    var r = new (window.ActiveXObject || XMLHttpRequest)('Microsoft.XMLHTTP')
    r.open('GET', url, true)

    r.onreadystatechange = function() {
      if (r.readyState === 4) {
        if (r.status === 200) {
          callback(r.responseText)
        }
        else {
          throw new Error('Could not load: ' + url + ', status = ' + r.status)
        }
      }
    }

    return r.send(null)
  }


  function globalEval(data) {
    if (data && /\S/.test(data)) {
      (window.execScript || function(data) {
        window['eval'].call(window, data)
      })(data)
    }
  }

});

